/**
 * 生成 n 进制的 m位 随机数
 */
export const randomNum = (n: number, m: number): number => {
  return ~~Math.random().toString(n).substr(2, m);
};
/**
 *
 * @param n 候补数字
 * @param length 补位长度
 * @returns string 部位后显示字符
 */
export const addZore = (n: number, length: number) => {
  return (Array(length).join("0") + n).substr(-length);
};
/**
 *
 * @param date 入参date
 * @returns 'YYYY-MM-DD'
 */
export const simpleFmtDate = (date: Date) => {
  let _date = date.toString();
  return _date.replace(/\b\d\b/g, "0$&");
};

/**
 * 格式化金额
 * @param s number
 * @returns string
 */
export const currency = (n: number) => {
  let s: string = parseFloat((n + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";
  let l = s.split(".")[0].split("").reverse(),
    r = s.split(".")[1];
  let t = "";
  for (let i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 === 0 && i + 1 !== l.length ? "," : "");
  }
  return t.split("").reverse().join("") + "." + r;
};

/**
 *
 * @param hex #e4393c
 * @param opacity 透明度 0~1
 * @returns rgba(xxx,xxx,xxx,opacity)
 */
export const hexToRgba = (hex: string, opacity: number): string => {
  return (
    "rgba(" +
    parseInt("0x" + hex.slice(1, 3)) +
    "," +
    parseInt("0x" + hex.slice(3, 5)) +
    "," +
    parseInt("0x" + hex.slice(5, 7)) +
    "," +
    opacity +
    ")"
  );
};

/**
 * 防抖
 * @param fn 防抖对象函数
 * @param rateTime 时间
 */
export const throttle = (fn: Function, rateTime: number) => {
  let timer: any = null;
  let prev = Date.now() - rateTime;
  return (...args: any[]) => {
    const remaining = rateTime - (Date.now() - prev);
    clearTimeout(timer);
    if (remaining <= 0) {
      fn(args);
      prev = Date.now();
    } else {
      timer = setTimeout(() => {
        fn(args);
      }, remaining);
    }
  };
};

/**
 *
 * @param d date
 * @param f YYYY-MM-DD or YYYY:MM:DD ....
 * @returns string
 */
export const fmtDate = (d: Date, f: string): string => {
  if (!d) return "";
  const t = {
    "y+": d.getFullYear(),
    "Y+": d.getFullYear(),
    "M+": d.getMonth() + 1,
    "d+": d.getDate(),
    "D+": d.getDate(),
    "H+": d.getHours(),
    "m+": d.getMinutes(),
    "s+": d.getSeconds(),
    "S+": d.getMilliseconds(),
  };
  let _t;
  let f_: string = f;
  Object.entries(t).forEach((item) => {
    const [k, v] = item;
    while (new RegExp(`(${k})`).test(f_)) {
      if (RegExp.$1.length === 1) {
        _t = v;
      } else {
        _t = ("0000000000".substring(0, RegExp.$1.length) + v).substr(
          `${v}`.length
        );
      }
      f_ = f_.replace(RegExp.$1, `${_t}`);
    }
  });
  return f_;
};
